<template>
  <div id="invTransferType">
    <Breadcrumb content="流转方式" />
    <div class="bodyContent">
      <Splitpanes>
        <!-- 左侧表格  -->
        <Pane size="65">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findTransferTypeList" @keyup="keyupEnter" @search-click="findTransferTypeList()"></vxe-input>
              <div class="smallToolTitle">类别</div>
              <vxe-select v-model="searchForm.businessType" @change="valueChangeEvent" clearable>
                <vxe-option v-for="transferTypeType in transferTypeTypeList" :key="transferTypeType.id" :label="transferTypeType.name" :value="transferTypeType.code"></vxe-option>
              </vxe-select>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="findTransferTypeList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addTransferTypeDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteTransferType"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="transferTypeTableRef" class="mytable-scrollbar transferTypeTableClazz" border="inner" align="left" height="auto" :data="transferTypeList" :loading="tloading" @current-change="transferTypeRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :row-style="rowStyle" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column field="businessTypeNa" title="业务类型" width="100">
                <template #default="{ row }">
                  <span>{{ row.businessTypeNa }}</span>
                </template>
              </vxe-column>
              <vxe-column field="transferCode" title="代码" width="120">
                <template #default="{ row }">
                  <span>{{ row.transferCode }}</span>
                </template>
              </vxe-column>
              <vxe-column field="transferName" title="名称">
                <template #default="{ row }">
                  <span>{{ row.transferName }}</span>
                </template>
              </vxe-column>
              <vxe-column field="inputCode" title="助记符">
                <template #default="{ row }">
                  <span>{{ row.inputCode }}</span>
                </template>
              </vxe-column>

              <vxe-column field="receiptsPrefix" title="单据前缀">
                <template #default="{ row }">
                  <span>{{ row.receiptsPrefix }}</span>
                </template>
              </vxe-column>
              <vxe-column field="receiptsYear" title="单据年份" width="120">
                <template #default="{ row }">
                  <span>{{ row.receiptsYear }}</span>
                </template>
              </vxe-column>
              <vxe-column field="receiptsMonth" title="单据月份" width="100">
                <template #default="{ row }">
                  <span>{{ row.receiptsMonth }}</span>
                </template></vxe-column>
            </vxe-table>
            <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                  'PrevJump',
                  'PrevPage',
                  'Number',
                  'NextPage',
                  'NextJump',
                  'Sizes',
                  'FullJump',
                  'Total'
                ]" @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
        <!-- 右侧表单 -->
        <Pane size="35">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="基础信息" name="first">
              <el-form ref="TransferTypeFormRef" :model="TransferTypeForm" :rules="TransferTypeFormRule" label-width="100px" inline-message>
                <el-row>
                  <el-col :span="12">
                    <el-form-item prop="businessType" label="业务类型">
                      <el-select v-model="TransferTypeForm.businessType" filterable placeholder="请选择">
                        <el-option v-for="businessType in transferTypeTypeList" :key="businessType.id" :label="businessType.name" :value="businessType.code"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="transferCode" label="流转方式编码">
                      <el-input type="text" v-model="TransferTypeForm.transferCode" placeholder="请输入流转方式编码	" clearable></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item prop="transferName" label="流转方式名称">
                      <el-input type="text" v-model="TransferTypeForm.transferName" placeholder="请输入流转方式名称	" @blur="getBdsResult()" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="inputCode" label="助记符">
                      <el-input type="text" v-model="TransferTypeForm.inputCode" placeholder="请输入助记符" clearable></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item prop="receiptsPrefix" label="单据前缀">
                      <el-input type="text" v-model="TransferTypeForm.receiptsPrefix" placeholder="请输入单据前缀" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="receiptsYear" label="单据年份">
                      <el-input type="text" v-model="TransferTypeForm.receiptsYear" placeholder="请输入单据年份" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="receiptsMonth" label="单据月份">
                      <el-input type="text" v-model="TransferTypeForm.receiptsMonth" placeholder="请输入单据月份" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="transferRules" label="编码规则">
                      <el-select v-model="TransferTypeForm.transferRules" filterable placeholder="请选择">
                        <el-option v-for="item in rulesList" :key="item.id" :label="item.ruleName" :value="item.ruleCode"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="receiptsMonth" label="是否财务记账">
                      <!-- <el-input type="text" v-model="TransferTypeForm.receiptsMonth" placeholder="请输入单据月份" clearable></el-input> -->
                      <vxe-checkbox v-model="TransferTypeForm.isFinaState" content="" :checked-value="1" :unchecked-value="0"></vxe-checkbox>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="showFlag" label="是否显示">
                      <!-- <el-input type="text" v-model="TransferTypeForm.receiptsMonth" placeholder="请输入单据月份" clearable></el-input> -->
                      <vxe-checkbox v-model="TransferTypeForm.showFlag"></vxe-checkbox>
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item class="form-footer">
                      <template #default>
                        <el-button type="primary" @click="saveTransferType('TransferTypeFormRef')">保存</el-button>
                        <el-button type="default" @click="resetForm()">重置</el-button>
                      </template>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
            <!-- <el-tab-pane label="评价登记" name="second" :disabled="isEmpty(transferTypeForm.id)">
              <InvSupplierAppraise ref="invSuppAppRef" />
            </el-tab-pane> -->
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
  <script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import InvSupplierAppraise from './InvSupplierAppraise.vue'; //失控记录图表
import { AppStore } from '@/stores/store'; //'../../../stores/store';
let store = AppStore();

// 全局变量定义区 ==========
// 根据关键字查询
let searchForm = {
  searchValue: '',
  businessType: ''
};
let tloading = ref(false); //加载状态
let activeName = ref('first');
let transferTypeList: any = reactive([]);
let transferTypeTypeList: any = reactive([]);
let rulesList: any = reactive([]);
let invSuppAppRef: any = ref(null);
let sltPurpose: any = ref({});

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 右侧基本信息表单
let TransferTypeForm = reactive({
  id: null,
  transferCode: '',
  transferName: '',
  businessType: '',
  inputCode: '',
  receiptsYear: '',
  receiptsMonth: '',
  transferRules: '',
  receiptsPrefix: '',
  storeManageId: '',
  isFinaState: 0,
  showFlag: true
});

let TransferTypeFormRule = {
  transferName: [
    {
      required: true,
      message: '请输入流转方式名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ],
  businessType: [{ required: true, message: '请选择业务类型' }]
};

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  getRulesList();
  findTransferTypeList(); // 获取质控规则表格数据
  getDictItemsList();
});
//获取检测方式数据字典
function getRulesList() {
  rulesList.length = 0;
  const url = '/api/rule/set/getSysRuleSetList';
  proxy.$http
    .get(url, { params: { moduleName: '试剂耗材' } })
    .then((res: any) => {
      Object.assign(rulesList, res.data);
    })
    .catch((err: any) => {});
}
//批量获取字典(获取对应质控水平)
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['transferBusinessType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const conKindType = dictTreeTypeItems.data.find((item) => item.code === 'transferBusinessType');
  transferTypeTypeList.push(...conKindType.detailDataList);
}
function tabHandleClick(tab) {
  if (tab.index == 1) {
    invSuppAppRef.value.initPage(TransferTypeForm.id);
  }
}
function findTransferTypeList() {
  tloading.value = true;
  transferTypeList.length = 0; //放入数据前清空数据
  const url = '/inv/transfer/type/findInvTransferTypePageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        businessType: searchForm.businessType,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      transferTypeList.push(...res.data.records);
      page.totalResult = res.data.total;
      const kn = transferTypeList.find((k) => k.id == sltPurpose.value.id);
      if (isEmpty(kn)) {
        transferTypeRowClick({ row: transferTypeList[0] }); //默认选中第一条数据
      } else {
        transferTypeRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function valueChangeEvent() {
  findTransferTypeList();
}

function saveTransferType(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (TransferTypeForm.id === null) {
      const url = '/inv/transfer/type/addInvTransferType';
      const transferType = {
        transferCode: TransferTypeForm.transferCode,
        transferName: TransferTypeForm.transferName,
        businessType: TransferTypeForm.businessType,
        inputCode: TransferTypeForm.inputCode,
        receiptsYear: TransferTypeForm.receiptsYear,
        receiptsMonth: TransferTypeForm.receiptsMonth,
        transferRules: TransferTypeForm.transferRules,
        receiptsPrefix: TransferTypeForm.receiptsPrefix,
        storeManageId: TransferTypeForm.storeManageId,
        isFinaState: TransferTypeForm.isFinaState,
        showFlag: TransferTypeForm.showFlag
      };
      proxy.$http
        .post(url, transferType)
        .then((res: any) => {
          VxeMessage('新增成功', VxeNotifyType.success);
          clearForm();
          sltPurpose.value.id = res.data.id;
          findTransferTypeList();
        })
        .catch((err: any) => {
          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/inv/transfer/type/editInvTransferType';
      const transferType = {
        id: TransferTypeForm.id,
        transferCode: TransferTypeForm.transferCode,
        transferName: TransferTypeForm.transferName,
        businessType: TransferTypeForm.businessType,
        inputCode: TransferTypeForm.inputCode,
        receiptsYear: TransferTypeForm.receiptsYear,
        receiptsMonth: TransferTypeForm.receiptsMonth,
        transferRules: TransferTypeForm.transferRules,
        receiptsPrefix: TransferTypeForm.receiptsPrefix,
        storeManageId: TransferTypeForm.storeManageId,
        isFinaState: TransferTypeForm.isFinaState,
        showFlag: TransferTypeForm.showFlag
      };
      proxy.$http
        .post(url, transferType)
        .then((res: any) => {
          VxeMessage('修改成功', VxeNotifyType.success);
          sltPurpose.value.id = res.data.id;
          setTimeout(() => {
            clearForm();
            findTransferTypeList();
          }, 50);
        })
        .catch((err: any) => {
          VxeMessage('修改失败', VxeNotifyType.error);
        });
    }
  });
}
function deleteTransferType() {
  const sltSuppliers = (proxy.$refs.transferTypeTableRef as any).getCheckboxRecords();
  if (!(sltSuppliers.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delSupplierList = sltSuppliers.filter((p: any) => !isEmpty(p.id));
        if (delSupplierList.length > 0) {
          const data = { transferTypeList: delSupplierList };
          const url = '/inv/transfer/type/batchDeleteInvTransferTypeList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findTransferTypeList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeSupplierList = sltSuppliers.filter((p: any) => isEmpty(p.id));
        if (removeSupplierList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.transferTypeTableRef;
          if ($Xtable) {
            for (const removeRow of removeSupplierList) {
              transferTypeList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findTransferTypeList();
  }
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findTransferTypeList();
}

// 点击设计模式表格当前行触发右侧表单变化
function transferTypeRowClick({ row }: any) {
  if (isEmpty(row)) {
    clearForm();
  } else {
    (proxy.$refs.transferTypeTableRef as any).setCurrentRow(row);
    setSupplierForm(row);
    if (activeName.value == 'second') {
      invSuppAppRef.value.initPage(TransferTypeForm.id);
    }
  }
}

// 新建
function addTransferTypeDialog() {
  clearForm();
  sltPurpose.value = {};
  (proxy.$refs.transferTypeTableRef as any).clearCurrentRow();
  activeName.value = 'first';
}

// 清空中间规则弹框表单
function clearForm() {
  TransferTypeForm.id = null;
  TransferTypeForm.storeManageId = '';
  TransferTypeForm.transferCode = '';
  TransferTypeForm.transferName = '';
  TransferTypeForm.inputCode = '';
  TransferTypeForm.businessType = '';
  TransferTypeForm.receiptsYear = '';
  TransferTypeForm.receiptsMonth = '';
  TransferTypeForm.transferRules = '';
  TransferTypeForm.receiptsPrefix = '';
  TransferTypeForm.showFlag = true;
}
function resetForm() {
  TransferTypeForm.storeManageId = '';
  TransferTypeForm.transferCode = '';
  TransferTypeForm.transferName = '';
  TransferTypeForm.inputCode = '';
  TransferTypeForm.businessType = '';
  TransferTypeForm.receiptsYear = '';
  TransferTypeForm.receiptsMonth = '';
  TransferTypeForm.transferRules = '';
  TransferTypeForm.receiptsPrefix = '';
  TransferTypeForm.showFlag = true;
}
// 编辑当前行规则
function setSupplierForm(row: any) {
  TransferTypeForm.id = row.id;
  TransferTypeForm.storeManageId = row.storeManageId;
  TransferTypeForm.transferCode = row.transferCode;
  TransferTypeForm.transferName = row.transferName;
  TransferTypeForm.inputCode = row.inputCode;
  TransferTypeForm.businessType = row.businessType;
  TransferTypeForm.receiptsYear = row.receiptsYear;
  TransferTypeForm.receiptsMonth = row.receiptsMonth;
  TransferTypeForm.transferRules = row.transferRules;
  TransferTypeForm.receiptsPrefix = row.receiptsPrefix;
  TransferTypeForm.isFinaState = row.isFinaState;
  TransferTypeForm.showFlag = row.showFlag;
  sltPurpose.value = row;
}

// 停用的行 红色背景高亮
const rowStyle = ({ row, rowIndex }) => {
  if (row.isStop) {
    return {
      backgroundColor: '#ffd5d5',
      color: 'red'
    };
  }
};

function getBdsResult() {
  TransferTypeForm.inputCode = funBdsJsResult('firstPinYinFun', TransferTypeForm.transferName);
}
</script>
  
  <style lang="scss" scoped>
#invTransferType {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          height: calc(100% - 40px);
          padding: 0;
          .el-tab-pane {
            height: 100%;
          }
          #pane-first {
            padding: 15px;
          }
        }
      }
    }
  }
}
</style>
  